﻿package ck.tool.stocksmart;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class stocksmart extends Activity {

  String METHOD_LIST = "http://hq.sinajs.cn/list=%s";
  static final private int ADD_NEW_STOCK  = Menu.FIRST;
  static final private int REFRESH_STOCK  = Menu.FIRST + 1;
  static final private int REFRESH_FREQ = Menu.FIRST + 2;
  static final private int BIND_SERVICE = Menu.FIRST + 3;
  static final private int UNBIND_SERVICE = Menu.FIRST + 4;
  static final private int REMOVE_STOCK = Menu.FIRST + 5;
  static final private int STOCK_ALARM  = Menu.FIRST + 6;
   
  private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY";
  private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY";
  private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY";
  
  private static final int SHOW_REFRESH_DIALOG = 1;
  private static final int DIALOG_TEXT_ENTRY = 2;
  
  private static final int ZERO_NOREFRESH = 0;
  private static final int ONE_TENSEC = 1;
  private static final int TWO_THIRTYSEC = 2;
  private static final int THREE_ONEMIN = 3;
  private static final int FOUR_SELFDEFINE = 4;
  
  private boolean addingNew = false;
  private ListView myListView;
  private EditText myEditText;
  private TextView myTextView;
  private RelativeLayout mylayout;
  private View myView;
  //private ImageButton btn;
  private Button btn;
  private StockFormat addtodb;
  private StockFormat addtodb_date;
  private ArrayList<StockFormat> stockItems;
  private StockMessage addonebyone;
  private ArrayList<StockMessage> myStockMessageList = new ArrayList<StockMessage>();
  ArrayList<Integer> index_ck = new ArrayList<Integer>();
  private int i;
  private int tempint;
  
  final ArrayList<String> stocklist = new ArrayList<String>();
  final ArrayList<String> stockdisplay = new ArrayList<String>();
  volatile ArrayAdapter<String> ck;
  
  //for repeat
  Calendar calendar = Calendar.getInstance();
  long test_time;
  
  //Used some temp variable parameter
  String content_http;
  Date temp_date;
  StockMessage tempstockmessage;
  String tempstring;
  String temp_stock;
  String stock_url;
  StockMessage display_data;
  String disp;
  String stock;
  float persent;
  float lastday;
  float now;
  float float_zero = 0;
  int per;
  int time;
  String n;
  public static String[] ss= new String[3];
  public static String[] filter_note = new String[2];
  public static String[] sck = new String[32];
  public static String[] ss_test = new String[2];
  
  //used for test SimpleDateFormat
  SimpleDateFormat myFmt;

  StockQuoteDBAdapter stockDBAdapter;
  Cursor stockListCursor;
  
  //use bind service
  private boolean mIsBound;
  private StockAlarmService mBoundService;
  /** Called when the activity is first created. */
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    
    //set the UI for user
    myListView = (ListView)findViewById(R.id.myListView);
    myEditText = (EditText)findViewById(R.id.myEditText);
    myTextView = (TextView) findViewById(R.id.myTextView);
    myTextView.setTextColor(Color.GREEN);
    btn = (Button)findViewById(R.id.myButton);
    //btn = (ImageButton)findViewById(R.id.myImageButton);
    //btn.setImageResource(R.drawable.searchck);
    
    //set EditText and Button view unable;
    //myEditText.setVisibility(View.GONE);
    //btn.setVisibility(View.GONE);
    myView = findViewById(R.id.widget50);
    //mylayout = (RelativeLayout)findViewById(R.id.widget50);
    //mylayout.setVisibility(View.GONE);
    myView.setVisibility(View.GONE);
    
    stockItems = new ArrayList<StockFormat>();
    //ArrayList<String> temp_stock = new ArrayList<String>();
    ck = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stockdisplay);
    myListView.setAdapter(ck);
    
    stockDBAdapter = new StockQuoteDBAdapter(this);

    // Open or create the database
    stockDBAdapter.open();

    myListView.setOnItemClickListener(new OnItemClickListener(){
	    public void onItemClick(AdapterView<?> parent, View arg1, int position,long id){
	    	position = stocklist.size() - position - 1;
	    	Log.v("stock", String.valueOf(position));
	    	temp_stock = (String) stocklist.get(position);
	    	Log.v("stock", temp_stock);
	    	stock_url = String.format(METHOD_LIST, temp_stock);
	    	if(httpsingle(stock_url))
	        {
	        	display_data = tempstockmessage;
	        }
            stockdisplay.set((int)id, getdisplay(display_data));
            ck.notifyDataSetChanged();
            //At the same time,refresh the stock current_price;
            
            stockDBAdapter.updateCurrentPrice(temp_stock,display_data.current_price);
	    }
    });
    btn.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
	    stock = myEditText.getText().toString();
            if(isNumeric(stock)){
                stock = stockCode(stock);
                stock_url = String.format(METHOD_LIST, stock);
	        if(httpsingle(stock_url))
	        {
	        	display_data = tempstockmessage;
	        }
	        else
	        {
	        	display_data = new StockMessage("NULL",0,0);
	        }
	        if((display_data.stock != "")&&(display_data.stock != "NULL")){
	    	    stocklist.add(stock);
	    	    stockdisplay.add(0, getdisplay(display_data));
	    	    ck.notifyDataSetChanged();
	    	    myEditText.setText("");
	    	    //At the same time Refresh the DataBase
	    	    //remember that u must use constructor to refresh a object
	    	    addtodb_date = new StockFormat(display_data.stock);
	    	    temp_date = addtodb_date.getCreated();
	    	    myFmt = new SimpleDateFormat("yy/MM/dd HH:mm");
	    	    Log.v("Test SimpleDataFormat", myFmt.format(temp_date));
	    	    addtodb = new StockFormat(stock, temp_date, display_data.current_price, display_data.current_price, float_zero, float_zero);
	    	    Log.v("Test the transform float", String.valueOf(addtodb.current_price));
	    	    stockDBAdapter.insertStock(addtodb);
	    	}
	    	if(display_data.stock == "")
	    	{
	    	    Toast.makeText(getApplicationContext(), "无此股票代码",
	    				Toast.LENGTH_SHORT).show();
	    	}
            }
            else
            {
            	Toast.makeText(getApplicationContext(), "请输入股票代码",
            			Toast.LENGTH_SHORT).show();
            }
            myView.setVisibility(View.GONE);	
        }
    });
    registerForContextMenu(myListView);
    restoreUIState();

    populateStockList();
  }
  
  private void populateStockList() {
    // Get all the todo list items from the database.
    stockListCursor = stockDBAdapter.getAllStockFormatCursor();
    startManagingCursor(stockListCursor);  
    // Updata the index
    updatestocklist();
    // Update the array.
    updatestockdisplay();
    
    stockListCursor.close();
  }

  private void updatestocklist() {
	  stockListCursor.requery();
	  //Because that every times the index_ck will be initialized first; use that to be part of 
	  //condition there while be a cann't end circle
	  stocklist.clear();
          if(stockListCursor.moveToFirst())
	  do {
		     String tmp = stockListCursor.getString(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_STOCK));
		     stocklist.add(tmp);
	     }while(stockListCursor.moveToNext());
	  }
  private void updatestockdisplay() {
	  stockListCursor.requery();

	  stockdisplay.clear();
	    
	  if (stockListCursor.moveToFirst())
	    do { 
	          stock = stockListCursor.getString(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_STOCK));
	          float current_price = stockListCursor.getFloat(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_CURRENT_PRICE));
	          tempstockmessage = new StockMessage(stock, current_price, float_zero);
	          stockdisplay.add(0, getdisplay(tempstockmessage));
	       } while(stockListCursor.moveToNext());
	  
	  ck.notifyDataSetChanged();
	}

  private void restoreUIState() {
    // Get the activity preferences object.
    SharedPreferences settings = getPreferences(0);

    // Read the UI state values, specifying default values.
    String text = settings.getString(TEXT_ENTRY_KEY, "");
    Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);

    // Restore the UI to the previous state.
    /*if (adding) {
      addNewItem();
      myEditText.setText(text);
    }*/
  }
  
  @Override
  public void onSaveInstanceState(Bundle outState) {
    outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition());

    super.onSaveInstanceState(outState);
  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
    int pos = -1;

    if (savedInstanceState != null)
      if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
        pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);

    myListView.setSelection(pos);
  }
  
  @Override
  protected void onPause() {
    super.onPause();
    
    // Get the activity preferences object.
    SharedPreferences uiState = getPreferences(0);
    // Get the preferences editor.
    SharedPreferences.Editor editor = uiState.edit();

    // Add the UI state preference values.
    editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString());
    editor.putBoolean(ADDING_ITEM_KEY, addingNew);
    // Commit the preferences.
    editor.commit();
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    // Create and add new menu items.
    MenuItem itemAdd = menu.add(0, ADD_NEW_STOCK, Menu.NONE,
                                R.string.add_new_stock);
    MenuItem itemRem = menu.add(0, REFRESH_STOCK, Menu.NONE,
                                R.string.refresh_stock);
    MenuItem itemFre = menu.add(0, REFRESH_FREQ,  Menu.NONE,
    							R.string.refresh_freq);
    MenuItem itemBind = menu.add(0, BIND_SERVICE, Menu.NONE,
    							R.string.bind_service);
    MenuItem itemUnbind = menu.add(0, UNBIND_SERVICE, Menu.NONE,
								R.string.unbind_service);

    // Assign icons
    itemAdd.setIcon(R.drawable.add_new_stock);
    itemRem.setIcon(R.drawable.refresh_stock);

    // Allocate shortcuts to each of them.
    itemAdd.setShortcut('0', 'a');
    itemRem.setShortcut('1', 'r');
    itemFre.setShortcut('2', 'f');
    itemBind.setShortcut('3', 'b');
    itemUnbind.setShortcut('4', 'u');
    return true;
  }
  
  @Override
  public void onCreateContextMenu(ContextMenu menu, 
                                  View v, 
                                  ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle(R.string.deleteandalarm);
    menu.add(0, REMOVE_STOCK, Menu.NONE, R.string.remove_stock);
    menu.add(0, STOCK_ALARM,  Menu.NONE, R.string.stock_alarm);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
	       super.onOptionsItemSelected(item);

//    int index = myListView.getSelectedItemPosition();

    switch (item.getItemId()) {
/*    case (REMOVE_TODO): {
        if (addingNew) {
          cancelAdd();
        } 
        else {
          removeItem(index);
        }
        return true;
      }*/
      case (BIND_SERVICE): { 
    	  /*startService(new Intent(stocksmart.this,
                  StockAlarmService.class));*/
    	  //Use the Service Start_not_Sticky
    	  //startService(new Intent("ck.tool.stocksmart.SERVICE"));
    	bindService(new Intent(stocksmart.this, 
                  	StockAlarmService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        return true; 
      }
      case (UNBIND_SERVICE): { 
    	  /*stopService(new Intent(stocksmart.this,
    			  StockAlarmService.class));*/
    	//Use the Service Start_not_Sticky
    	  stopService(new Intent("ck.tool.stocksmart.SERVICE"));
    	  if (mIsBound) {
              // Detach our existing connection.
              unbindService(mConnection);
              mIsBound = false;
              Log.v("Hello ","I stopped the service!!!");
          }
    	  //Log.v("Hello ","I stopped the service!!!");
          return true; 
        }
      case (ADD_NEW_STOCK): { 
        addNewItem();
        Log.v("First ","I arrived here!!!");
        return true; 
      }
      case (REFRESH_STOCK): {
    	   new Thread() 
			{
				@Override
				public void run() {
					try {
	        	          m_handler.sendEmptyMessage(0);
					} catch (Exception e) {
						Log.v("Test thread", "Thread is not OK!");
					}
				}
			}.start();
    	  //refreshAll();
    	  return true;
      }
      case (REFRESH_FREQ): {
    	  //Intent i = new Intent(this, StockRefreshfreq.class);
    	  //startActivity(i);
    	  showDialog(SHOW_REFRESH_DIALOG);
    	  
      }
    }
    return false;
  }
  
  @Override
  public boolean onContextItemSelected(MenuItem item) {  
	   super.onContextItemSelected(item);
    switch (item.getItemId()) {
      case (REMOVE_STOCK): {
        AdapterView.AdapterContextMenuInfo menuInfo;
        menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        //String task = menuInfo.toString();
        int index = menuInfo.position;
        Log.v("index is ", stocklist.get(stocklist.size() - index - 1));
        temp_stock = stocklist.get(stocklist.size() - index - 1);
        stockDBAdapter.removeByStock(temp_stock);
        //refresh the screen display
        updatestocklist();
        updatestockdisplay();
        return true;
      }
      case (STOCK_ALARM): {
    	  //Start an intent there to start an activity can return an value;
    	  AdapterView.AdapterContextMenuInfo menuInfo;
          menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
          //String task = menuInfo.toString();
          int index = menuInfo.position;
          Log.v("index is ", stocklist.get(stocklist.size() - index - 1));
          temp_stock = stocklist.get(stocklist.size() - index - 1);
    	  Intent intent=new Intent();
          intent.putExtra("extra", temp_stock);
          intent.setClass(stocksmart.this, StockAlarm.class);
          stocksmart.this.startActivity(intent);
      }
    }
    return false;
  }
  
  @Override
  public void onDestroy() {
	// Close the database
	stockDBAdapter.close();
	
	
    super.onDestroy();
  }
  
  //add Dialog
  @Override
  protected Dialog onCreateDialog(int id) {
	  switch (id){
	  case SHOW_REFRESH_DIALOG:
	  return new AlertDialog.Builder(stocksmart.this)
      .setIcon(R.drawable.icon)
      .setTitle(R.string.alert_dialog_single_choice)
      .setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

              /* User clicked on a radio button do some stuff */
        	  tempint = whichButton;
        	  Log.v("choose the dialog", String.valueOf(whichButton));
          }
      })
      .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

              /* User clicked Yes so do some stuff */
        	  switch(tempint){
        	  case ZERO_NOREFRESH:
        	  {
        		  Log.v("Haha","you got 0!");
        		  break;
        	  }
        	  case ONE_TENSEC:
        	  {
				  calendar.setTimeInMillis(System.currentTimeMillis());
				  calendar.add(Calendar.SECOND, 10);
				  test_time = calendar.getTimeInMillis();
				  Log.v("Current time is ", String.valueOf(test_time));
						  new Thread() 
					  	  {
						  	@Override
						  	public void run() {
						  		while(true)
						  		{
						  			if(System.currentTimeMillis() == test_time){
						  				try {
						  					m_handler.sendEmptyMessage(0);
						  				} catch (Exception e) {
						  					Log.v("Test thread", "Thread is not OK!");
						  				}
						  				calendar.add(Calendar.SECOND, 10);
									  	test_time = calendar.getTimeInMillis();
									  	Log.v("Now time is",String.valueOf(System.currentTimeMillis()));
						  			}
						  			if(tempint != ONE_TENSEC)
									{
						  				break;
									}
						  		}
						  	}
					  	}.start();
				  break;
        	  }
        	  case TWO_THIRTYSEC:
        	  {
        		  calendar.setTimeInMillis(System.currentTimeMillis());
				  calendar.add(Calendar.SECOND, 30);
				  test_time = calendar.getTimeInMillis();
				  Log.v("Current time is ", String.valueOf(test_time));
						  new Thread() 
					  	  {
						  	@Override
						  	public void run() {
						  		while(true)
						  		{
						  			if(System.currentTimeMillis() == test_time){
						  				try {
						  					m_handler.sendEmptyMessage(0);
						  				} catch (Exception e) {
						  					Log.v("Test thread", "Thread is not OK!");
						  				}
						  				calendar.add(Calendar.SECOND, 30);
									  	test_time = calendar.getTimeInMillis();
									  	Log.v("Now time is",String.valueOf(System.currentTimeMillis()));
						  			}
						  			if(tempint != TWO_THIRTYSEC)
									{
						  				break;
									}
						  		}
						  	}
					  	}.start();
				  break;
        	  }
        	  case THREE_ONEMIN:
        	  {
        		  calendar.setTimeInMillis(System.currentTimeMillis());
				  calendar.add(Calendar.SECOND, 60);
				  test_time = calendar.getTimeInMillis();
				  Log.v("Current time is ", String.valueOf(test_time));
						  new Thread() 
					  	  {
						  	@Override
						  	public void run() {
						  		while(true)
						  		{
						  			if(System.currentTimeMillis() == test_time){
						  				try {
						  					m_handler.sendEmptyMessage(0);
						  				} catch (Exception e) {
						  					Log.v("Test thread", "Thread is not OK!");
						  				}
						  				calendar.add(Calendar.SECOND, 60);
									  	test_time = calendar.getTimeInMillis();
									  	Log.v("Now time is",String.valueOf(System.currentTimeMillis()));
						  			}
						  			if(tempint != THREE_ONEMIN)
									{
						  				break;
									}
						  		}
						  	}
					  	}.start();
				  break;
        	  }
        	  case FOUR_SELFDEFINE:
        	  {
        		  showDialog(DIALOG_TEXT_ENTRY);
        		  break;
        	  }
        	  }
        	  Log.v("choose the OK", String.valueOf(whichButton));
			  Log.v("choose the dialog", String.valueOf(tempint));
          }
      })
      .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

              /* User clicked No so do some stuff */
        	  Log.v("choose the cancel", String.valueOf(whichButton));
          }
      })
     .create();
	  case DIALOG_TEXT_ENTRY:
		  LayoutInflater factory = LayoutInflater.from(stocksmart.this);
          final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
          return new AlertDialog.Builder(stocksmart.this)
              .setIcon(R.drawable.icon)
              .setTitle(R.string.alert_dialog_single_choice)
              .setView(textEntryView)
              .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
  
                      /* User clicked OK so do some stuff */
                	 EditText tempEditTexta = (EditText)textEntryView.findViewById(R.id.min_edit);
                 	 EditText tempEditTextb = (EditText)textEntryView.findViewById(R.id.sec_edit);
                	 String min = tempEditTexta.getText().toString();
                	 String sec = tempEditTextb.getText().toString();
                	 Log.v("The min is ",tempEditTexta.getText().toString());
                	 if(isSec(min)&&isSec(sec))
                	 {
                		time = 60*(Integer.valueOf(min)) + Integer.valueOf(sec);
                	 }
                	 else{
                		 time = 0;
                		 tempint = 0;
                		 Toast.makeText(getApplicationContext(), "请输入数字！",
     	                        Toast.LENGTH_SHORT).show();
                	 }
                	 
                	 calendar.setTimeInMillis(System.currentTimeMillis());
   				  	 calendar.add(Calendar.SECOND, time);
   				  	 test_time = calendar.getTimeInMillis();
   				     Log.v("Current time is ", String.valueOf(time));
   						  new Thread() 
   					  	  {
   						  	@Override
   						  	public void run() {
   						  		while(true)
   						  		{
   						  			if(System.currentTimeMillis() == test_time){
   						  				try {
   						  					m_handler.sendEmptyMessage(0);
   						  				} catch (Exception e) {
   						  					Log.v("Test thread", "Thread is not OK!");
   						  				}
   						  				calendar.add(Calendar.SECOND, time);
   									  	test_time = calendar.getTimeInMillis();
   									  	Log.v("Now time is",String.valueOf(System.currentTimeMillis()));
   						  			}
   						  			if(tempint != FOUR_SELFDEFINE)
   									{
   						  				break;
   									}
   						  		}
   						  	}
   					  	}.start();
                  }
              })
              .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {

                      /* User clicked cancel so do some stuff */
                  }
              })
              .create();
      }
	  return null;
  }
  
  private void cancelAdd() {
    addingNew = false;
    myEditText.setVisibility(View.GONE);
  }
  
  //use other thread to refresh the UI thread
  public final Handler m_handler = new Handler() 
	{
		@Override
		public void handleMessage(final Message msg) {

			refreshAll();

		}
	};
  private void addNewItem() {
    addingNew = true;
    myView.setVisibility(View.VISIBLE);
    //mylayout.setVisibility(View.VISIBLE);
    //myEditText.setVisibility(View.VISIBLE);
    myEditText.requestFocus();
    //btn.setVisibility(View.VISIBLE);
    btn.requestFocus();
    Intent intent = new Intent(stocksmart.this, StockAlarmService.class);
	stocksmart.this.startService(intent);
  }
  
  synchronized private void refreshAll() {
	  makefullstring();
	  String temp_refresh = String.format(METHOD_LIST, stock_url);
	  Log.v("refreshAll in stockurl",temp_refresh);
	  if(httpcont(temp_refresh))
	  {
		  if(myStockMessageList.size() != 0)
		  {
			  stockdisplay.clear();
			  for(i = 0; i < myStockMessageList.size(); i++)
			  {
				  Log.v("test"+ String.valueOf(i), getdisplay(myStockMessageList.get(i)));
				  stockdisplay.add(0,getdisplay(myStockMessageList.get(i)));
			  }
			  ck.notifyDataSetChanged();
			  //Refresh all database
			  for(i = 0; i < stocklist.size(); i++)
			  {
				  temp_stock = stocklist.get(i);
				  Log.v("Hello",temp_stock + String.valueOf(i));
				  stockDBAdapter.updateCurrentPrice(temp_stock,myStockMessageList.get(i).current_price);
			  }
		  }
	  }
  }
  
  private void makefullstring() {
	  String temp_makefull = "";
	  if(stocklist.size()!=0){
		  for(i = 0; i < stocklist.size(); i++)
		  {
			  if(i == 0)
			  {
				  temp_makefull += stocklist.get(i);
			  }
			  else
			  {
				  temp_makefull += (","+stocklist.get(i));
			  }
		  }
		  stock_url = temp_makefull;
	  }
	  else
	  {
		  stock_url = null;
	  }
      
	  Log.v("All String in the stocklist", stock_url);
  }
  private void removeItem(int _index) {
/*    // Items are added to the listview in reverse order, so invert the index.
    //toDoDBAdapter.removeTask(todoItems.size()-_index);
	findIndex();
	Log.v("Test","todoItems.size() = "+ String.valueOf(todoItems.size()));
	Log.v("Test_index","_index = "+ String.valueOf(_index));
	Log.v("Test_index size is","_index = "+ String.valueOf(index_ck.size()));
	Log.v("The get is ",String.valueOf(index_ck.get(0)));
	toDoDBAdapter.removeTask(index_ck.get(todoItems.size()-_index - 1));
        updateArray(); */
  }
  // Used for add new stock to the DataBase
  protected boolean httpsingle(String stock_url) {
      //String para
      //DefaultHttpClient
      DefaultHttpClient httpclient = new DefaultHttpClient();
      //HttpGet
      HttpGet httpget = new HttpGet(stock_url);
      //ResponseHandler
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      
      try {
      	      content_http = httpclient.execute(httpget, responseHandler);
      	      Log.v("test for content_http", content_http);
      	      tempstockmessage = getwanted(content_http);
      	      return true;
	      
	  } catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Cannot connect the internet!",
                        Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			return false;
		}
      }
      
  // Used for Refresh all StockList in the DataBase
  protected boolean httpcont(String stock_url) {
      //String para
      //DefaultHttpClient
	  if(stock_url != null)
	  {
		  DefaultHttpClient httpclient_all = new DefaultHttpClient();
		  //HttpGet
		  HttpGet httpget_all = new HttpGet(stock_url);
		  Log.v("Stock_Url",stock_url);
		  //ResponseHandler
		  ResponseHandler<String> responseHandler_all = new BasicResponseHandler();
      
		  try {
			  	String content = httpclient_all.execute(httpget_all, responseHandler_all);
			  	String[] content_array = content.split("var");
			  	for(i = 1; i < content_array.length; i++)
			  	{
			  		tempstring = content_array[i];
			  		Log.v("The arry list length is ",content_array[i]);
			  		
			  	} 
			  	myStockMessageList.clear();
			  	Log.v("The arry list length is ",String.valueOf(content_array.length));
			  	for(i = 1; i < content_array.length; i++)
			  	{
			  		tempstring = content_array[i];
			  		tempstockmessage = getwanted(tempstring);
			  		myStockMessageList.add(tempstockmessage);
			  	} 
		  } catch (Exception e) {
			  Toast.makeText(getApplicationContext(), "Cannot connect the internet!",
                        Toast.LENGTH_SHORT).show();
			  e.printStackTrace();
			  return false;
		  }
		return true;
	  }
	  else
	  {
		  Toast.makeText(getApplicationContext(), "No stock to Refresh!",
                  Toast.LENGTH_SHORT).show();
		  return false;
	  }
	}
  public StockMessage getwanted(String content){
  	 	
  	n = content;
  	Log.v("test for content", content);
	filter_note = n.split(";");
	ss_test = filter_note[0].split("=");
	ss = n.split("\"");
	if(!ss_test[1].equals("\"\""))
	{
	    sck = ss[1].split(",");
	    lastday = Float.parseFloat(sck[2]);
	    now = Float.parseFloat(sck[3]);
	    Log.v("Test the String", sck[3]);
	    Log.v("Test the float", String.valueOf(now));
	    per = (int) ((now-lastday)*10000/lastday);
	    persent = (float)(per)/100;
	    if(now != 0)
	    {
	    	display_data = new StockMessage(sck[0],now,persent);
	        display_data.range = persent;
	    }
	    else
	    {
	    	display_data = new StockMessage(sck[0],now,float_zero);
	    }
	}
	else
	{
		display_data = new StockMessage("",float_zero,float_zero);
	}
	return display_data;
  	}
  public boolean isNumeric(String str){
	Pattern pattern = Pattern.compile("[603][0][012]\\d{3}");
	Matcher isNum = pattern.matcher(str);
	if( !isNum.matches() )
	{
		return false;
	}
	return true;
	}
  public String stockCode(String temp_stock){
  	int temp;

  	temp = Integer.valueOf(temp_stock).intValue();
        if(temp >= 600000){
        	temp_stock = "sh" + temp_stock;
          }
          else
          {
          	temp_stock = "sz" + temp_stock;
          }
          return temp_stock;
  	}
  public String getdisplay(StockMessage temp){
        String display;
        display = temp.stock + "        " + temp.current_price + "        " + temp.range +"%";
        return display;
        }
  public boolean isSec(String str){
		Pattern pattern = Pattern.compile("\\d+?");
		Matcher isNum = pattern.matcher(str);
		if( !isNum.matches() )
		{
			return false;
		}
		return true;
		}
  //Intent intent = new Intent(DemoNotification.this, WatchService.class);
	//intent.putExtra("delta", delta);
	//DemoNotification.this.startService(intent);
  //	DemoNotification.this.startService(intent);
  private ServiceConnection mConnection = new ServiceConnection() {
      public void onServiceConnected(ComponentName className, IBinder service) {
          // This is called when the connection with the service has been
          // established, giving us the service object we can use to
          // interact with the service.  Because we have bound to a explicit
          // service that we know is running in our own process, we can
          // cast its IBinder to a concrete class and directly access it.
          mBoundService = ((StockAlarmService.LocalBinder)service).getService();
          
          // Tell the user about this for our demo.
          Toast.makeText(stocksmart.this, R.string.stock_alarm_service_connected,
                  Toast.LENGTH_SHORT).show();
      }

      public void onServiceDisconnected(ComponentName className) {
          // This is called when the connection with the service has been
          // unexpectedly disconnected -- that is, its process crashed.
          // Because it is running in our same process, we should never
          // see this happen.
          mBoundService = null;
          Toast.makeText(stocksmart.this, R.string.stock_alarm_service_disconnected,
                  Toast.LENGTH_SHORT).show();
      }
  };
}